#include <stdio.h>
#include "Patient.h"
#include <string.h>
#include<stdlib.h>
#define capacity 300

int testjourentree(patient *pat)
{
	int test=0;
	if((pat->dateentree.mois==4)||(pat->dateentree.mois==6)||(pat->dateentree.mois==9)||(pat->dateentree.mois==11))
		{
		if(pat->dateentree.jour>30)
			{test=1;}
		}
	else if ((pat->dateentree.mois==2)&&(test==0))
		{
		if(pat->dateentree.jour>29)
			{test=1;}
		}
	else
		if(pat->dateentree.jour>31)
			{test=1;}
return test;
}

int testjoursortie(patient *pat)
{
	int test=0;
	if((pat->datesortie.mois==4)||(pat->datesortie.mois==6)||(pat->datesortie.mois==9)||(pat->datesortie.mois==11))
		{
		if(pat->datesortie.jour>30)
			{test=1;}
		}
	else if ((pat->datesortie.mois==2)&&(test==0))
		{
		if(pat->datesortie.jour>29)
			{test=1;}
		}
	else
		if(pat->datesortie.jour>31)
			{test=1;}
return test;
}

int comparercinpat(patient *pat)
{ FILE *f;
  FILE *y;
  patient p;
  int res=0,res1=0,res2=0;
  f=fopen("fichierpatient","ab");
  if (f!=NULL)
	{
         while((fread(&p,sizeof(patient),1,f)!=0) && (res1==0))
 	    {
	      if(pat->cin==p.cin)
	       res1=1;
 	    }
 	}
  y=fopen("tmp3","ab");
  if ((y!=NULL) || (res1==0))
	{
         while((fread(&p,sizeof(patient),1,y)!=0) && (res2==0))
 	    {
	      if(pat->cin==p.cin)
	       res2=1;
 	    }
 	}
if( (res1==1) || (res2==1))
{res=1;}
return res;
}


int comparerdate(patient *pat)
{
int c=0;
if(pat->dateentree.annee<pat->datesortie.annee)
{ c=1;}
else if (pat->dateentree.annee==pat->datesortie.annee)
	{if (pat->dateentree.mois<pat->datesortie.mois)
		{c=1;}
		else if (pat->dateentree.mois==pat->datesortie.mois)
			{if (pat->dateentree.jour<pat->datesortie.jour)
				{c=1;}
			}
	}
return c;
} 

int longueurpat(int valeur)
{
	int l= 0;

	while(valeur !=0)
	{
		l++;
		valeur = valeur / 10;
	}
 return l;
}




void enregistrerpatient(char fichier[], patient *pat)
{
  FILE *f;
  f=fopen(fichier,"ab");
  if (f!=NULL){
  fwrite(pat,sizeof(patient),1,f);}
  fclose(f);
}




void supprimerpatient( char fichier[],int ID)
{	
	char tmp3[]="tmp3.txt";
	char tmp[]="tmp.txt";
	FILE *f ;
	FILE *t ;
	FILE *y;
	patient p;
	f=fopen(fichier,"rb") ;
	t=fopen(tmp,"wb") ;
	y=fopen(tmp3,"a+");
	if (f!= NULL && t!=NULL)
		{
			while(fread(&p,sizeof(patient),1,f)!=0)
				{
					if( ID!=p.ID)
						{ fwrite(&p,sizeof(patient),1,t);}
					if(ID==p.ID)
						{fwrite(&p,sizeof(patient),1,y);}
				}
		}
	fclose(y);
	fclose(f) ;
	fclose(t) ;
	f=fopen(fichier,"wb") ;
	t=fopen(tmp,"rb") ;
	while(fread (&p,sizeof(patient),1,t)!=0)
		{fwrite(&p,sizeof(patient),1,f) ;}
	fclose(f) ;
	fclose(t) ;
}

void initpatients(char fichier[])
{
 	FILE *f;
 	f=fopen(fichier,"wb");
 	fclose(f);
}


